package com.fingard.dsp.bank.directbank.spdb01;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptData;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptDataHelper;
import com.fingard.dsp.bank.directConfig.ReceiptProConfig;
import com.fingard.dsp.bank.directbank.bankInterface.IReceiptPro;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.dsp.bank.sepro.ReceiptPro;
import com.fingard.dsp.task.command.SyncReceipt;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;
import com.fingard.util.PdfGenerateUtil;
import com.fingard.util.ZipHelper;

import java.io.File;
import java.math.BigDecimal;
import java.util.Date;

public class SPDB01ReceiptPro extends SPDB01Base implements IReceiptPro {
    @Override
    public RetAtsReceipt qryReceiptOneDay(ReceiptProConfig pConfig, ReqQryReceipt pReqReceipt, Date pOneDay) throws Exception {
        try {
            String qryDay8 = Format.Date8Format.format(pOneDay);
            String saveDirPathTemp = pConfig.getSaveSubDir(pReqReceipt.reqHeader, pOneDay) + File.separator + qryDay8 + File.separator + ReceiptPro.getTransID();
            FileHelper.mkdirsIfNotExists(saveDirPathTemp);
            WriteBankLogLn("浦发回单文件下载目录：" + saveDirPathTemp);
            String downFile = getBankConfig().getValueAsString("receiptPrefix", "Receipt_") + qryDay8 + ".zip";
            WriteBankLogLn("下载的回单文件名：" + downFile);
            String[] tmpEndRet = downFileFromBank(downFile, saveDirPathTemp);
            if (tmpEndRet[0].length() == 0) {
                String zipFile = saveDirPathTemp + File.separator + downFile;
                if (new File(zipFile).exists()) {
                    WriteBankLogLn("开始解压文件:" + zipFile);
                    ZipHelper.unzipFile(zipFile, saveDirPathTemp);
                    WriteBankLogLn("文件解压已完成.");
                    File depressDir = new File(saveDirPathTemp);
                    File[] deFiles = depressDir.listFiles();
                    if (deFiles != null && deFiles.length > 0) {
                    } else {
                        WriteBankLogLn("解压后文件夹" + saveDirPathTemp + "下为空");
                    }
                } else {
                    WriteBankLogLn(downFile + "--该文件下载失败");
                }
            } else {
                WriteBankLogLn("的回单下载失败,请重新下载 原因: " + tmpEndRet[1]);
            }
            //调用提取pdf文件的方法
            getPdfFiles(pConfig, pReqReceipt, pOneDay, saveDirPathTemp + File.separator + getBankConfig().getValueAsString("receiptPrefix", "Receipt_") + qryDay8);

            WriteBankLogLn("删除" + saveDirPathTemp);
            FileHelper.deleteRecursive(saveDirPathTemp);
        } catch (Exception ex) {
            WriteBankLogLn(ex);
        }

        return null;
    }

    private void getPdfFiles(ReceiptProConfig pConfig, ReqQryReceipt pReqReceipt, Date pOneDay, String pReceiptDir) {
        ReceiptDataHelper receiptHelper = null;//回单数据保存类，分区分表
        try {
            receiptHelper = new ReceiptDataHelper(pReqReceipt.reqHeader.tenant, pOneDay);
            File receiptDir = new File(pReceiptDir);

            int[] retVals = getPdfLoop(pConfig, pReqReceipt, pOneDay, receiptHelper, receiptDir);
            //[0]总数 [1]新增 [2]已存在
            WriteBankLogLn("目录" + pReceiptDir + "\r\n遍历总数" + retVals[0] + "，新增" + retVals[1] + "条，已存在" + retVals[2] + "条");
            if (retVals[1] > 0) {
                SyncReceipt.resetDelayCounter();
            }

        } catch (Exception ex) {
            this.WriteBankLogLn(ex);
        } finally {
            if (receiptHelper != null) {
                receiptHelper.close();
            }
        }
    }

    /**
     * 下载的日期目录中提取该账号对应的html，再提取pdf
     * pRelativeSaveDir 相对文件夹目录
     */
    private int[] getPdfLoop(ReceiptProConfig pConfig, ReqQryReceipt pReqReceipt, Date pOneDay, ReceiptDataHelper pReceiptHelper, File pDir) {
        int[] retVals = new int[3];
        retVals[0] = 0;//总pdf个数
        retVals[1] = 0;//新增
        retVals[2] = 0;//已存在
        File[] files = pDir.listFiles();
        for (File eachFile : files) {
            try {
                if (eachFile.isDirectory()) {
                    int[] subVals = getPdfLoop(pConfig, pReqReceipt, pOneDay, pReceiptHelper, eachFile);
                    retVals[0] = retVals[0] + subVals[0];
                    retVals[1] = retVals[1] + subVals[1];
                    retVals[2] = retVals[2] + subVals[2];
                }

                String eachName = eachFile.getName().toLowerCase();
                if (eachName.endsWith(".pdf")) {
                    retVals[0] = retVals[0] + 1;
                    //1202020209900311818_20191118_19322000001.PDF
                    String[] nameAndExt = StringHelper.splitFileNameAndExt(eachName);
                    String[] nameSp = nameAndExt[0].split("_");
//                    if(nameSp.length != 5){
//                        WriteBankLogLn("文件名"+eachName+"不符合预期格式");
//                        continue;
//                    }
                    ReceiptData eachData = new ReceiptData();
                    eachData.istNbr = nameSp[2];
                    eachData.ownAct = nameSp[0];
                    eachData.setBusDate(pOneDay);

                    //重命名
                    String renameToPath = pConfig.getSaveSubDir(pReqReceipt.reqHeader, pOneDay) + File.separator + String.valueOf(eachData.busDate) + File.separator + eachData.ownAct;
                    FileHelper.mkdirsIfNotExists(renameToPath);
                    renameToPath += File.separator + eachFile.getName();
                    File destFile = new File(renameToPath);
                    boolean reResult;
                    if (destFile.exists()) {
                        reResult = true;
                    } else {
                        reResult = eachFile.renameTo(destFile);
                    }
                    if (reResult) {
                        WriteBankLogLn("正在解析回单文件：" + destFile.getAbsolutePath());
                        String[] pdfStrArr = PdfGenerateUtil.readPDFTable(destFile.getAbsolutePath(), 1000, 800).split("\r\n");
                        String receiptCode = "";
                        if (pdfStrArr[0].trim().equals("上海浦东发展银行业务凭证/回单")) {
                            receiptCode = pdfStrArr[1].substring(pdfStrArr[1].indexOf("回单编号") + 5, pdfStrArr[1].indexOf("交易流水") - 1);
                        } else if (pdfStrArr[0].trim().equals("上海浦东发展银行电子缴税付款凭证")) {
                            receiptCode = pdfStrArr[1].substring(pdfStrArr[1].indexOf("回单编号") + 5, pdfStrArr[1].indexOf("回单类型") - 1);
                        } else {
                            throw new RuntimeException();
                        }
                        eachData.receiptNo = receiptCode;
                        eachData.cur = pReqReceipt.actCur;
                        eachData.amount = new BigDecimal(getAmountStr(pdfStrArr).replaceAll(",", ""));
                        eachData.localFile = StringHelper.getRelativePath(destFile.getAbsolutePath(), pConfig.localSaveMainDir);
                        eachData.srcFile = eachFile.getName();
                        eachData.busRef = eachData.receiptNo;
                        eachData.bank = "310";
                        eachData.srcSys = "SPDB01";

                        if (!String.valueOf(eachData.busDate).equals(nameSp[1])) {
                            WriteBankLogLn("提取的日期" + nameSp[1] + "不符合预期" + String.valueOf(eachData.busDate) + "，回单文件名:" + eachFile.getName());
                            eachData.downInfo = nameSp[1] + "-文件中提取的日期";
                        }

                        eachData.downState = "2";
                        eachData.downTime = new Date();
                        /**下载信息，如果失败则为失败原因*/
                        eachData.downInfo = "下载成功";
                        /**上传状态：指文件从银行端下载完成后，上传至ftp或ats或oss或客制化文件服务的状态，1未上传；2已上传；3上传失败；4上传中*/
                        eachData.upState = "1";
                        /**推送状态：指文件上传完成后，回单数据推送至ats或客制化平台的状态，1未推送；2已推送；3推送失败；4推送中*/
                        eachData.pushState = "1";
                        /**创建时间*/
                        eachData.createdOn = new Date();
                        /**最后修改时间*/
                        eachData.lastModifiedOn = new Date();
                        /**版本号*/
                        eachData.rowVersion = 1;

                        int inRe = pReceiptHelper.insertIfNotExist(eachData, true);
                        if (inRe > 0) {
                            retVals[1] = retVals[1] + 1;
                        } else if (inRe == 0) {
                            retVals[2] = retVals[2] + 1;
                        }
                        WriteBankLogLn(eachData.receiptNo + "写入数据库，影响行数：" + inRe);
                    } else {
                        WriteBankLogLn(eachData.receiptNo + "重命名失败：\r\n" + eachFile.getAbsolutePath() + "\r\n重命名为：\r\n" + renameToPath);
                    }
                }
            } catch (Exception ex) {
                WriteBankLogLn("解析回单文件失败，请检查回单文件内容是否正确。");
                WriteBankLogLn(ex, eachFile.getAbsolutePath());
            }
        }
        return retVals;
    }
}
